<template>
  <div class="nil-drawer">
    <el-scrollbar class="nil-drawer-body">
      <el-form ref="form" :model="formData" label-width="120px">
        <el-form-item label="角色 KEY">
          <el-input
            v-model="formData.roleKey"
            v-if="isChange"
            readonly
          ></el-input>
          <el-input v-model="formData.roleKey" v-else></el-input>
        </el-form-item>

        <el-form-item label="角色名称">
          <el-input v-model="formData.roleName"></el-input>
        </el-form-item>

        <el-form-item label="菜单权限">
          <el-scrollbar height="300px" style="width: 100%">
            <el-tree
              :data="menus"
              ref="roleMenusTree"
              show-checkbox
              node-key="id"
              :default-checked-keys="nowRoleMenuKeys"
              :props="defaultProps"
              :default-expand-all="true"
              :expand-on-click-node="false"
              :check-on-click-node="true"
            />
          </el-scrollbar>
        </el-form-item>

        <el-form-item>
          <el-button :loading="loading" type="primary" @click="save">{{
            isChange ? "修改" : "创建"
          }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </div>
</template>

<script setup>
import api from "@/http/api";
import { ADMIN_MENU_LIST, ADMIN_MENU_FOR_ROLE } from "@/http/uri";
import { useMenuStore } from "@/stores/menu";
import { onBeforeMount, onMounted, reactive, ref } from "vue";

const props = defineProps({
  loading: Boolean,
  isChange: Boolean,
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const defaultProps = {
  children: "children",
  label: "name",
};

// 获取菜单数节点 ref
const roleMenusTree = ref();

const nowRoleMenuKeys = ref([]);
const menus = ref([]);

const formData = reactive(props.data);

const emit = defineEmits(["save", "change", "cancel"]);

function save() {
  const treeChecked = roleMenusTree.value.getCheckedKeys();
  const treeChecked_half = roleMenusTree.value.getHalfCheckedKeys();
  treeChecked.push(...treeChecked_half);
  if (props.isChange) {
    emit("change", formData, treeChecked);
  } else {
    emit("save", formData, treeChecked);
  }
}

function cancel() {
  emit("cancel");
}

const menuStore = useMenuStore();

// 拉取菜单列表
function initMenus() {
  if (menuStore.menus.length == 0) {
    api.GET(ADMIN_MENU_LIST).then((res) => {
      if (res.success) {
        const data = res.data;
        const target = {};
        data.forEach((item) => {
          if (!target[item.pid]) {
            target[item.pid] = [];
          }
          const arr = target[item.pid];
          arr.push(item);
        });
        const temp = target[0];
        if (temp) {
          temp.forEach((item) => {
            item.children = target[item.id];
          });
        }
        menus.value.push(...temp);
        menuStore.setMenus(temp);
      }
    });
  } else {
    menus.value.push(...menuStore.menus);
  }
}

onBeforeMount(() => {
  initMenus();
});

function initUserMenus() {
  // 如果是修改模式 加载用户的菜单
  if (props.isChange) {
    api
      .GET(ADMIN_MENU_FOR_ROLE, {
        role: props.data.id ?? "",
      })
      .then((res) => {
        let temp = [];
        const target = {};
        res.data.forEach((item) => {
          if (!target[item.pid]) {
            target[item.pid] = [];
          }
          target[item.pid].push(item.id);
        });

        console.log("nilbrains === >target === >", target);
        const filter = target[0];
        if (filter) {
          filter.forEach((item) => {
            if (target[item]) {
              temp.push(...target[item]);
            } else {
              temp.push(item);
            }
          });
        }

        // TODO why it unuse
        nowRoleMenuKeys.value.push(...temp);
        console.log("[ nowRoleMenuKeys.value ] >", nowRoleMenuKeys.value);
        roleMenusTree.value?.setCheckedKeys(nowRoleMenuKeys.value, true);
      });
  }
}

// const clearSelect = () => {
//   nowRoleMenuKeys.value = [];
//   roleMenusTree.value?.setCheckedKeys([], false);
// };

onMounted(() => {
  // 第一次 加载 菜单已选 内容
  initUserMenus();
});
</script>

<style lang="scss" scoped></style>
